<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/2/20
 * Time: 17:56
 */

namespace app\admin\controller;

use think\Config as ThinkConfig;
use think\response\Redirect;
use think\Response;
use think\exception\HttpResponseException;

use app\common\controller\Base;

class CheckLogin extends Base
{
    protected $userId;
    public function __construct()
    {
        parent::__construct();
        $userId = (int)session('userId');
        if($userId<=0){
            $response = $this->request->isAjax() || $this->request->isPost() ? Response::create(['code' => self::CODE_ILL, 'msg' => '用户信息失效，请重新登录'], 'json') : new Redirect(ThinkConfig::get('nologin_redirect'));
            throw new HttpResponseException($response);
        }
        //检查权限
        $controller = $this->request->controller();
        $action = $this->request->action();
        if($controller != 'Index' && $controller != 'File') {
            $key = '/' . $this->cc_format($controller) . '/' . $action;
            $rules = session('rules');
            if (!(!empty($rules) && isset($rules[$key]))) {
                $response = $this->request->isAjax() || $this->request->isPost() ? Response::create(['code' => self::CODE_FAIL, 'msg' => '你没有权限'], 'json') : new Redirect(ThinkConfig::get('nopermission_redirect'));
                throw new HttpResponseException($response);
            }
        }

        $this->userId = $userId;
    }

    private function cc_format($name){
        $temp_array = array();
        for($i=0;$i<strlen($name);$i++){
            $ascii_code = ord($name[$i]);
            if($ascii_code >= 65 && $ascii_code <= 90){             //大写转小写
                if($i == 0){
                    $temp_array[] = chr($ascii_code + 32);
                }else{
                    $temp_array[] = '_'.chr($ascii_code + 32);
                }
            }else{
                $temp_array[] = $name[$i];
            }
        }
        return implode('',$temp_array);
    }
}
